package com.hyq.learn.security.cipher;

import com.hyq.learn.security.warrper.ContentCachingRequest;
import jakarta.servlet.Filter;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.lang.Nullable;

import java.io.IOException;

/**
 * @author : heyuqin
 * @since : 2024/03/06 14:15
 */
public abstract class AbstractCipherFilter implements Filter {
    protected final Logger logger = LoggerFactory.getLogger(AbstractCipherFilter.class);

    protected final KeyProvider keyProvider;

    protected final CipherAlgorithm cipherAlgorithm;

    protected final CipherDecision cipherDecision;

    protected final String headerName;

    public AbstractCipherFilter(KeyProvider keyProvider, CipherAlgorithm cipherAlgorithm,
                                @Nullable CipherDecision cipherDecision, String headerName) {
        this.keyProvider = keyProvider;
        this.cipherAlgorithm = cipherAlgorithm;
        this.cipherDecision = cipherDecision;
        this.headerName = headerName;
    }

    /**
     * 解密请求
     * @param request
     */
    protected void decryptRequest(ContentCachingRequest request) throws IOException {
        byte[] sourceRequestBody = request.getPayload();
        if (sourceRequestBody == null || sourceRequestBody.length == 0) {
            return ;
        }

        byte[] decryptedRequestBody;
        try {
            String payloadString = request.getPayloadString();
            byte[] bytes = Base64.isBase64(payloadString) ? Base64.decodeBase64(payloadString) : request.getPayload();
            decryptedRequestBody = cipherAlgorithm.decryption(bytes, keyProvider.get(request));
        }catch (Exception e){
            throw new RuntimeException("Failed to decrypt the request body", e);
        }
        request.setPayload(decryptedRequestBody);
    }
}
